﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace WP8_PPS.Helpers
{
    /// <summary>
    /// Static class to generically convert from an enumeration to strings and back
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// Convert enumeration to a list of strings
        /// </summary>
        /// <typeparam name="TEnum">Enumeration to convert</typeparam>
        /// <returns>List of strings representing the enumerations in the enumerator</returns>
        public static IEnumerable<string> GetNames<TEnum>() where TEnum : struct
        {
            var type = typeof(TEnum);
            if (!type.IsEnum)
                throw new ArgumentException(String.Format("Type '{0}' is not an enum", type.Name));

            return (
              from field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
              where field.IsLiteral
              select field.Name)
            .ToList<string>();
        }

        /// <summary>
        /// Convert a string to the enumeration of the enumerator passed in
        /// </summary>
        /// <typeparam name="TEnum">Enumeration to convert</typeparam>
        /// <param name="value">String in the enumeration</param>
        /// <returns>Enumeration with the selection</returns>
        public static TEnum GetEnum<TEnum>(string value) where TEnum : struct
        {
            try
            {
                var type = (TEnum)Enum.Parse(typeof(TEnum), value);
                return type;
            }
            catch( Exception e )
            {
                // Don't know how to handle this.  The way I've coded this particular solution it should never happen
                // But for code reuse here you go!
                throw new Exception();
            }
        }
    }
}
